package com.guaju.yueshangLife.utils;

import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.GradientDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;


import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.guaju.yueshangLife.R;
import com.guaju.yueshangLife.global.BaseApplication;
import com.lljjcoder.style.citylist.Toast.ToastUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.Reader;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static android.content.Context.TELEPHONY_SERVICE;
import static android.text.TextUtils.isEmpty;

/**
 * Created by chunlei.lu on 17/5/12.
 */

public class Utils {

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    // 两次点击按钮之间的点击间隔不能少于1000毫秒
    private static final int MIN_CLICK_DELAY_TIME = 1000;
    private static long lastClickTime;

    public static boolean isFastClick() {
        boolean flag = false;
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
            flag = true;
        }
        lastClickTime = curClickTime;
        return flag;
    }

    public static String getDeviceId(Context context) {
        StringBuilder deviceId = new StringBuilder();
        // 渠道标志
//        String channel = readMetaDataIntStr(context, "CHANNEL");
//        deviceId.append(channel);
        try {
            String androidId = getUniquePsuedoID();
            //IMEI（imei）
            String imei = "";
            TelephonyManager tm = null;
            try {
                tm = (TelephonyManager) context.getSystemService(TELEPHONY_SERVICE);
                if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                    imei = tm.getDeviceId();
                }
            } catch (Exception e){}
            if (!isEmpty(imei)) {
                if(imei.equals("000000000000000")){
                    if(!TextUtils.isEmpty(androidId)){
                        deviceId.append("androidId");
                        deviceId.append(androidId);
                    }
                } else {
                    deviceId.append("imei");
                    deviceId.append(imei);
                }
                Log.e("getDeviceId : ", deviceId.toString());
                return deviceId.toString();
            }
            //序列号（sn）
            String sn = tm.getSimSerialNumber();
            if (!isEmpty(sn)) {
                deviceId.append("sn");
                deviceId.append(sn);
                Log.e("getDeviceId : ", deviceId.toString());
                return deviceId.toString();
            }
            //生成一个id：随机码
            DeviceUuidFactory deviceUuidFactory = new DeviceUuidFactory(context);
            String uuid = deviceUuidFactory.getDeviceUuid().toString();
            if (!isEmpty(uuid)) {
                deviceId.append("id");
                deviceId.append(uuid);
                Log.e("getDeviceId : ", deviceId.toString());
                return deviceId.toString();
            }
            //wifi mac地址
            WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo info = wifi.getConnectionInfo();
            String wifiMac = info.getMacAddress();
            if (!isEmpty(wifiMac)) {
                deviceId.append("wifi");
                deviceId.append(wifiMac);
                Log.e("getDeviceId : ", deviceId.toString());
                return deviceId.toString();
            }
        } catch (Exception e) {
            //e.printStackTrace();
            DeviceUuidFactory deviceUuidFactory = new DeviceUuidFactory(context);
            deviceId.append("id").append(deviceUuidFactory.getDeviceUuid().toString());
        }
        Log.e("getDeviceId : ", deviceId.toString());
        return deviceId.toString();
    }

    /**
     * 获取CHANNEL
     */
    public static String readMetaDataIntStr(Context context, String keyName) {
        String channel = ChannelUtil.getChannel(context);
        if (TextUtils.isEmpty(channel)) {
            Object object = null;
            try {
                String packageName = context.getPackageName();
                ApplicationInfo info = context.getPackageManager().getApplicationInfo(packageName, PackageManager.GET_META_DATA);
                object = (Object) info.metaData.get(keyName);
                channel = object.toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return channel;
    }


    /**
     * 隐藏输入法
     *
     * @param paramContext
     * @param paramEditText
     */
    public static void hideSoftKeyboard(Context paramContext,
                                        EditText paramEditText) {
        ((InputMethodManager) paramContext
                .getSystemService(Context.INPUT_METHOD_SERVICE))
                .hideSoftInputFromWindow(paramEditText.getWindowToken(), 0);
    }

    /**
     * 显示输入法
     *
     * @param paramContext
     * @param paramEditText
     */
    public static void showSoftKeyborad(Context paramContext,
                                        EditText paramEditText) {
        ((InputMethodManager) paramContext
                .getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(
                paramEditText, InputMethodManager.SHOW_FORCED);
    }

    public static void hideKeyboard(View v) {
        InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
        }
    }

    public static void showKeyboard(Activity context) {
        try {
            InputMethodManager m = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            if (!m.isActive()) {
                m.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 检查是不是手机号
     *
     * @param mobiles
     * @return
     */
    public static boolean isMobileNO(String mobiles) {
		Pattern p = Pattern.compile("^((1[0-9]))\\d{9}$"); // 2018年08月13日  去掉号段验证
//        Pattern p = Pattern.compile("^((1[34578]))\\d{9}$");
        Matcher m = p.matcher(mobiles);

        return m.matches();

    }

    /**
     * 检查是不是验证码
     *
     * @param authCode
     * @return
     */
    public static boolean isSmsCodeNO(String authCode) {
        Pattern p = Pattern.compile("^[0-9]*$");

        Matcher m = p.matcher(authCode);

        return m.matches();

    }

    /**
     * 检测用户输入的Email格式
     *
     * @param mail
     * @return
     */
    public static boolean checkEmail(String mail) {
        String regex = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(mail);
        return m.find();
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 将px值转换为sp值，保证文字大小不变
     *
     * @param pxValue
     * @param （DisplayMetrics类中属性scaledDensity）
     * @return
     */
    public static int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     * @param spValue
     * @param （DisplayMetrics类中属性scaledDensity）
     * @return
     */
    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 数字转万，大于一万按万为单位显示
     */
    public static String numberToWan(int num){
        if (num > 10000){
            double result = (double) num / 10000;
            DecimalFormat df = new DecimalFormat("#.00");
            return String.valueOf(df.format(result))+"万";
        }else {
            return String.valueOf(num);
        }
    }

//    /**
//     * 创建快捷方式
//     *
//     * @param context
//     */
//    public static void addShortcut(Context context) {
//
//        String ACTION_INSTALL_SHORTCUT = "com.android.launcher.action.INSTALL_SHORTCUT";
//        // 快捷方式要启动的包
//        // Intent intent = gotoWhere(context);
//        Intent intent = new Intent(context, RosterStartActivity.class);
//        // 设置快捷方式的参数
//        Intent shortcutIntent = new Intent(ACTION_INSTALL_SHORTCUT);
//        // 设置名称
//        shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, context
//                .getResources().getString(R.string.app_name));
//        // 设置启动 Intent
//        shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
//        // 设置图标
//        shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
//                Intent.ShortcutIconResource.fromContext(context,
//                        R.drawable.icon));
//        // 只创建一次快捷方式
//        shortcutIntent.putExtra("duplicate", false);
//        context.sendBroadcast(shortcutIntent);
//    }

    /**
     * 获取网络类型
     *
     * @param context
     * @return
     */
    public static int getNetworkType(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager
                    .getActiveNetworkInfo();
            if (mNetworkInfo != null && mNetworkInfo.isAvailable()) {
                return mNetworkInfo.getType();
            }
        }
        return -1;
    }

    /**
     * 判断网络连接
     *
     * @param context
     * @return
     */
    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager
                    .getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

//    public static void highlightContent(Context paramContext,
//                                        Spannable paramSpannable) {
//        try {
//            Matcher localMatcher = Pattern.compile("\\[(\\S+?)\\]").matcher(
//                    paramSpannable);
//
//            while (true) {
//                if (!localMatcher.find())
//                    return;
//                int i = localMatcher.start();
//                int j = localMatcher.end();
//                String str = localMatcher.group(1);
////				Integer localInteger = TSFaceView.facesKeyString.get(str);
////				if ((localInteger.intValue() <= 0) || (localInteger == null))
////					continue;
//                Log.d(TAG, "i=" + i + ",j=" + j);
//                paramSpannable.setSpan(
//                        new ImageSpan(paramContext, str.length()),
//                        i, j, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//            }
//        } catch (Exception e) {
//            Log.d("TSUtils", e.toString());
//        }
//    }

    public static String getFromString(int from) {
        String fromString = "来自网站";
        switch (from) {
            case 0:
                fromString = "来自网站";
                break;
            case 1:
                fromString = "来自手机网页版";
                break;
            case 2:
                fromString = "来自Android客户端";
                break;
            case 3:
                fromString = "来自iPhone客户端";
                break;
            case 4:
                fromString = "来自iPad客户端";
                break;
            case 5:
                fromString = "来自Windows.Phone客户端";
                break;
        }
        return fromString;
    }

    /**
     * 过滤 bom
     *
     * @param in
     * @return
     */
    public static String JSONFilterBom(String in) {
        // consume an optional byte order mark (BOM) if it exists
        if (in != null && in.startsWith("\ufeff")) {
            in = in.substring(1);
        }
        return in;
    }

    /**
     * 基本功能：过滤所有以"<"开头以">"结尾的标签
     *
     * @param str
     * @return String
     */
    public static String filterHtml(String str) {
        if (str == null) {
            return "";
        }
        String regxpForHtml = "<([^>]*)>"; // 过滤所有以<开头以>结尾的标签
        Pattern pattern = Pattern.compile(regxpForHtml);
        Matcher matcher = pattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        boolean result1 = matcher.find();
        while (result1) {
            matcher.appendReplacement(sb, "");
            result1 = matcher.find();
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    public static String replaceBlank(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

//    @SuppressLint("NewApi")
//    public static void initTraffic(Context context) {
//        if (Build.VERSION.SDK_INT < 8) {
//            return;
//        }
//        PackageManager packageManager = context.getPackageManager();
//        long receive = 0;
//        long send = 0;
//        try {
//            ApplicationInfo applicationInfo = packageManager
//                    .getApplicationInfo("com.chuangyejia.dhroster", ApplicationInfo.FLAG_SYSTEM);
//            int uid = applicationInfo.uid;
//            receive = TrafficStats.getUidRxBytes(uid);
//            send = TrafficStats.getUidTxBytes(uid);
//            // PrefsManager.putLong(context,
//            // context.getString(R.string.traffic_send), send);
//            // PrefsManager.putLong(context,
//            // context.getString(R.string.traffic_receive), receive);
//            System.err.println("receive " + receive);
//            System.err.println("send " + send);
//        } catch (PackageManager.NameNotFoundException e) {
//            e.printStackTrace();
//        }
//    }


    public static boolean isNull(String str) {
        if (str != null && !"".equals(str) && !str.equals("null")) {
            return true;
        } else {
            return false;
        }
    }

    public static String isNullStr(String str) {
        if (str != null && !"".equals(str) && !str.equals("null")) {
            return str;
        } else {
            return "";
        }
    }

    /**
     * 获取屏幕宽度
     *
     * @param context
     * @return
     */
    public static int getWindowWidth(Context context) {
        return context.getResources().getDisplayMetrics().widthPixels;
    }

    /**
     * 获取屏幕高度
     *
     * @param context
     * @return
     */

    public static int getWindowHeight(Context context) {
        return context.getResources().getDisplayMetrics().heightPixels;
    }


    /**
     * 判断intent是否含有bundle
     *
     * @param activity
     * @return
     */
    public static boolean hasBundle(Activity activity) {
        Bundle bundle = activity.getIntent().getExtras();
        if (bundle != null) {
            return true;
        }
        return false;
    }

    /**
     * 描述：是否是邮箱.
     *
     * @param str 指定的字符串
     * @return 是否是邮箱:是为true，否则false
     */
    public static Boolean isEmail(String str) {
        Boolean isEmail = false;
        String expr = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        if (str.matches(expr)) {
            isEmail = true;
        }
        return isEmail;
    }


//    public static SpannableString handlerHtmlContent(final Context context, final String content) {
//        SpannableString spStr = null;
//        if (!TextUtils.isEmpty(content)) {
//            final String cs = new String(content);
//            CharSequence sequence = Html.fromHtml(cs);//处理富文本
//            if (sequence.length() > 2) {
//                CharSequence endStr = sequence.subSequence(sequence.length() - 2, sequence.length());
//                if (endStr.toString().equals("\n\n")) {
//                    sequence = sequence.subSequence(0, sequence.length() - 2);
//                }
//            }
//            HashMap<Integer, String> urls = StringUtils.getURLMatcher(sequence.toString());
//            spStr = new SpannableString(sequence);
//            if (urls.size() > 0) {
//                Iterator<Map.Entry<Integer, String>> iter = urls.entrySet().iterator();
//                while (iter.hasNext()) {
//                    Map.Entry<Integer, String> entry = iter.next();
//                    int start = entry.getKey();
//                    final String url = entry.getValue();
//                    int end = start + url.length();
//                    spStr.setSpan(new ClickableSpan() {
//                        @Override
//                        public void updateDrawState(TextPaint ds) {
//                            super.updateDrawState(ds);
//                            ds.setColor(Color.parseColor("#0988fb"));       //设置文件颜色
//                            ds.setUnderlineText(true);      //设置下划线
//                        }
//
//                        @Override
//                        public void onClick(View widget) {
//                            Bundle bundle = new Bundle();
//                            String resultUrl = "";
//                            if (!url.startsWith("http")) {
//                                resultUrl = "http://" + url;
//                            } else {
//                                resultUrl = url;
//                            }
//                            GeneralWebViewActivity.startActivity((Activity) context, "", resultUrl);
//                        }
//                    }, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//                }
//            }
//        }
//        return spStr;
//    }

    public static void changeShapeBgColor(View view, String color16) {
        GradientDrawable myGrad = (GradientDrawable) view.getBackground();
        myGrad.setColor(Color.parseColor(color16));
    }

    public static void changeShapeStroke(View view, int px, String color16) {
        GradientDrawable myGrad = (GradientDrawable) view.getBackground();
        myGrad.setStroke(px, Color.parseColor(color16));
    }

    public static final int CORNER_TOP_LEFT = 1;
    public static final int CORNER_TOP_RIGHT = 1 << 1;
    public static final int CORNER_BOTTOM_LEFT = 1 << 2;
    public static final int CORNER_BOTTOM_RIGHT = 1 << 3;
    public static final int CORNER_ALL = CORNER_TOP_LEFT | CORNER_TOP_RIGHT | CORNER_BOTTOM_LEFT | CORNER_BOTTOM_RIGHT;

    /**
     * 设置图片---自定义图片4个角中的指定角为圆角
     *
     * @param cornerRadius 圆角像素大小
     * @param corners      自定义圆角:
     *                     以下参数为corners中静态变量:
     *                     <p>
     *                     CORNER_NONE　无圆角
     *                     <p>
     *                     CORNER_ALL 全为圆角
     *                     <p>
     *                     CORNER_TOP_LEFT | CORNER_TOP_RIGHT | CORNER_BOTTOM_LEFT | CORNER_BOTTOM_RIGHT　指定圆角（选其中若干组合  ）
     */
    public static Bitmap makeRoundCorner(int corners, Bitmap bitmap, int cornerRadius) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        int color = 0xff424242;
        Paint paint = new Paint();
        Rect rect = new Rect(0, 0, width, height);
        RectF rectF = new RectF(rect);
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, cornerRadius, cornerRadius, paint);

        int notRoundedCorners = corners ^ CORNER_ALL;
        //哪个角不是圆角我再把你用矩形画出来
        if ((notRoundedCorners & CORNER_TOP_LEFT) != 0) {
            canvas.drawRect(0, 0, cornerRadius, cornerRadius, paint);
        }
        if ((notRoundedCorners & CORNER_TOP_RIGHT) != 0) {
            canvas.drawRect(rectF.right - cornerRadius, 0, rectF.right, cornerRadius, paint);
        }
        if ((notRoundedCorners & CORNER_BOTTOM_LEFT) != 0) {
            canvas.drawRect(0, rectF.bottom - cornerRadius, cornerRadius, rectF.bottom, paint);
        }
        if ((notRoundedCorners & CORNER_BOTTOM_RIGHT) != 0) {
            canvas.drawRect(rectF.right - cornerRadius, rectF.bottom - cornerRadius, rectF.right, rectF.bottom, paint);
        }
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);

        return output;
    }


    public static String getTime(){

        long time= System.currentTimeMillis()/1000;//获取系统时间的10位的时间戳

        String str= String.valueOf(time);

        return str;

    }

    /**
     * V2.0 用户中心相关接口加密
     */
    public static String getAES(Map dataMap) {
        AESCrypt aesCrypt = null;
        Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
        String output_str = "";
        String aesData = "";
        try {
            aesCrypt = new AESCrypt(AESCrypt.USER_CENTER_POST_KEY);
            output_str = aesCrypt.encrypt(gson.toJson(dataMap));
            aesData = new String(Base64.encode(output_str.getBytes("utf-8"), Base64.NO_WRAP),"utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return aesData;
    }

    /**
     * 判断 用户是否安装微信客户端
     */
    public static boolean isWeixinAvilible(Context context) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }
        return false;
    }

    public static File getVideoCacheDir(Context context) {
        return new File(context.getExternalCacheDir(), "video-cache");
    }

    public static void cleanVideoCacheDir(Context context) {
        File videoCacheDir = getVideoCacheDir(context);
        cleanDirectory(videoCacheDir);
    }

    private static void cleanDirectory(File file) {
        if (!file.exists()) {
            return;
        }
        File[] contentFiles = file.listFiles();
        if (contentFiles != null) {
            for (File contentFile : contentFiles) {
                delete(contentFile);
            }
        }
    }

    private static void delete(File file) {
        if (file.isFile() && file.exists()) {
            deleteOrThrow(file);
        } else {
            cleanDirectory(file);
            deleteOrThrow(file);
        }
    }

    private static void deleteOrThrow(File file){
        if (file.exists()) {
            boolean isDeleted = file.delete();
            if (!isDeleted) {
                try {
                    throw new IOException(String.format("File %s can't be deleted", file.getAbsolutePath()));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static String getUniquePsuedoID() {
        String m_szDevIDShort = "";
        String serial = "";
        try {
             m_szDevIDShort = "35" + (Build.BOARD.length() % 10) + (Build.BRAND.length() % 10) + (Build.CPU_ABI.length() % 10) + (Build.DEVICE.length() % 10) + (Build.MANUFACTURER.length() % 10) + (Build.MODEL.length() % 10) + (Build.PRODUCT.length() % 10);
            serial = Build.class.getField("SERIAL").get(null).toString();
            return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
        }
        catch (Exception e) {
            serial = "serial"; // some value
        }
        return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
    }

    /**
     * 获取手机的MAC地址
     *
     * @return
     */
    public static String getAppMac() {
        String str = "";
        String macSerial = "";
        try {
            Process pp = Runtime.getRuntime().exec(
                    "cat /sys/class/net/wlan0/address ");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);

            for (; null != str;) {
                str = input.readLine();
                if (str != null) {
                    macSerial = str.trim();// 去空格
                    break;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (TextUtils.isEmpty(macSerial)) {
            try {
                return loadFileAsString("/sys/class/net/eth0/address")
                        .toUpperCase().substring(0, 17);
            } catch (Exception e) {
                e.printStackTrace();

            }

        }
        return macSerial;
    }

    public static String loadFileAsString(String fileName) throws Exception {
        FileReader reader = new FileReader(fileName);
        String text = loadReaderAsString(reader);
        reader.close();
        return text;
    }

    public static String loadReaderAsString(Reader reader) throws Exception {
        StringBuilder builder = new StringBuilder();
        char[] buffer = new char[4096];
        int readLength = reader.read(buffer);
        while (readLength >= 0) {
            builder.append(buffer, 0, readLength);
            readLength = reader.read(buffer);
        }
        return builder.toString();
    }

    public static Bitmap readBitMap(Context context, int resId){
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true;
        //获取资源图片
        InputStream is = context.getResources().openRawResource(resId);
        return BitmapFactory.decodeStream(is,null,opt);
    }

    //保存文件到指定路径
    public static boolean saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "DHTopNews" + File.separator + "Images";
        File appDir = new File(storePath);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            //通过io流的方式来压缩保存图片
            boolean isSuccess = bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();

            //把文件插入到系统图库
            MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);

            //保存图片后发送广播通知更新数据库
            Uri uri = Uri.fromFile(file);
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            if (isSuccess) {
                Looper.prepare();
                ToastUtil.show("保存成功！");
                Looper.loop();
                return true;
            } else {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 判断用户是否开启了通知权限
     */
    public static boolean isOpenNotif(){
        NotificationManagerCompat manager = NotificationManagerCompat.from(BaseApplication.getInstance().getApplicationContext());
        boolean isOpened = manager.areNotificationsEnabled();
        return isOpened;
    }

    /**
     * 跳转到设置页面
     */
    public static void jumpToSetting(Activity activity){
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", BaseApplication.getInstance().getPackageName(), null);
        intent.setData(uri);
        activity.startActivity(intent);
    }



    /**
     * 判断某一个类是否存在任务栈里面
     *
     * @return
     */
    public static boolean isExsitMianActivity(Context context, Class<?> cls) {
        Intent intent = new Intent(context, cls);
        ComponentName cmpName = intent.resolveActivity(context
                .getPackageManager());
        boolean flag = false;
        if (cmpName != null) { // 说明系统中存在这个activity
            ActivityManager am = (ActivityManager) context
                    .getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> taskInfoList = am.getRunningTasks(10);
            for (ActivityManager.RunningTaskInfo taskInfo : taskInfoList) {
                if (taskInfo.baseActivity.equals(cmpName)) { // 说明它已经启动了
                    flag = true;
                    break; // 跳出循环，优化效率
                }
            }
        }
        return flag;
    }


    /**
     * 复制文字到剪切板
     */
    public static void copyLabel(Context context,String text){
        //获取剪贴板管理器：
        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        // 创建普通字符型ClipData
        ClipData mClipData = ClipData.newPlainText("Label", text);
        // 将ClipData内容放到系统剪贴板里。
        cm.setPrimaryClip(mClipData);
        ToastUtil.show("信息已复制！");
    }
}
